package fr.utbm.aiechat.activities;

import java.util.ArrayList;

import fr.utbm.aiechat.Network;
import fr.utbm.aiechat.R;
import fr.utbm.aiechat.structures.Channel;
import fr.utbm.aiechat.structures.Conversation;
import fr.utbm.aiechat.structures.Message;
import fr.utbm.aiechat.structures.User;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MessActivity extends Activity implements OnClickListener
{
	public Channel chan;
	public Button sendBtn;
	public EditText edittxt;
	
	// Array adapter for the conversation thread
    public ArrayAdapter<String> mConversationArrayAdapter;
    // Layout Views
    private ListView mConversationView;
	
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        //get back the chan selected before
        Bundle b = getIntent().getExtras();
        this.chan =  Network.getInstance().getChannelFromConvers(b.getInt("chanSelected"));
        //System.out.println("chanObject = " + chan);
        //add send button and edit text
        //ListView lv = getListView();
        //LayoutInflater inflater = getLayoutInflater();
        //View footer = (View)inflater.inflate(R.layout.mess_footer, lv, false);
        //lv.addFooterView(footer, null, false);
        
        
        setContentView(R.layout.convtest);
        // Initialize the array adapter for the conversation thread
        
        
        mConversationArrayAdapter = Network.getInstance().getMessListByUniqueID(this, chan.getUniqueID());
        
        //mConversationArrayAdapter =
        mConversationView = (ListView) findViewById(R.id.in);
        mConversationView.setAdapter(mConversationArrayAdapter);
        
        Network.getInstance().Messages.put(chan.getUniqueID(), mConversationArrayAdapter);
        
        
        
        
       /* Network.getInstance().createMessAdapter(this.chan.getUniqueID());
        
        ListAdapter la = Network.getInstance().Messages.get(this.chan.getUniqueID()); 
        setListAdapter(la);
        
        int nbLines = 0;
        if(la.getCount() > 4){
        	nbLines = la.getCount() - 4; 
        }
        la.registerDataSetObserver(new DataSetObserverPerso(nbLines, lv));*/
        
        //add all message of selected chan to the messAdapter
      /*  for (int i = 0 ; i < MessActivity.chan.getListMessage().size() ; i++) {
        	Message mess = MessActivity.chan.getListMessage().get(i);
        	Network.getInstance().addMessage(MessActivity.chan.getUniqueID(),mess);
        }*/
        this.sendBtn = (Button) this.findViewById(R.id.button_send);
        this.edittxt = (EditText) this.findViewById(R.id.edit_text_out);
        this.sendBtn.setOnClickListener(this);
    }
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mess_menu, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	int id = item.getItemId();
        // Handle item selection
        switch (id)
        {
	        case R.id.invit:
	        	ArrayList<User> listUser = new ArrayList<User>();
	        	int nb = Network.getInstance().Users.getCount();

	        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        	builder.setTitle("Liste Utilisateur");
	        	//Construct user list only users who aren't in the channel
	        	for  (int i = 0 ; i < nb ; i++) {	
	        		User user = Network.getInstance().Users.getItem(i);
	        		//only if user is not in this chan
	        		if (!this.chan.containsUser(user)) {
	        			listUser.add(user);
	        		}
	
	        	}
	        	final CharSequence[] items = new CharSequence[listUser.size()];
	        	boolean[] tableBool = new boolean[listUser.size()] ;
	        	for (int i = 0 ; i < listUser.size() ; i++) {
		        	items[i] = listUser.get(i).getName();
		        	tableBool[i] = false;
	        	}
	        	builder.setMultiChoiceItems(items, tableBool, new DialogInterface.OnMultiChoiceClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which, boolean isChecked) {
						// TODO Auto-generated method stub
						
					}
				});
	        	builder.setPositiveButton( "OK", new DialogButtonClickHandler(tableBool,listUser,chan));

	        	AlertDialog alert = builder.create();
	        	alert.show();
	        	return true;
	        case R.id.quit:
	        	//Left channel
	        	User me = Network.getInstance().me;
	        	//Send all that i leave chan
	        	for (int i = 0 ; i < this.chan.getListUser().size() ; i++) {
	        		Network.getInstance().quitChan(this.chan.getListUser().get(i),me,chan.getUniqueID());
	        	}
	        	//remove the conversation
	        	Conversation.removeConversByUniquedId(chan.getUniqueID());
	        	//stop current activity
    			finish();
	        	return true;
	        default:
                return super.onOptionsItemSelected(item);
        }
    }
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	  if (!edittxt.getText().toString().equals("")) {
    	  //TODO: put real date
    	  Message mess = new Message(Network.getInstance().me,null,edittxt.getText().toString());
    	  //send the sauce
    	  for (int i = 0 ; i < this.chan.getListUser().size() ; i++) {
    		  Network.getInstance().sendMessage(mess,this.chan,this.chan.getListUser().get(i));
    	  }
    	  edittxt.setText("");
      }
	}
}
class DialogButtonClickHandler implements DialogInterface.OnClickListener
{
	boolean[] tableBool;
	ArrayList<User> listUser ;
	Channel chan ;
	public DialogButtonClickHandler(boolean[] tableBool, ArrayList<User> listUser, Channel chan) {
		this.tableBool = tableBool;
		this.listUser = listUser;
		this.chan = chan;
	}

	public void onClick( DialogInterface dialog, int clicked )
	{
		switch( clicked )
		{
			case DialogInterface.BUTTON_POSITIVE:
				for (int i = 0 ; i < tableBool.length ; i++) {
					//if userSelected send Invit
					if (tableBool[i]) {
						this.chan.addUser(listUser.get(i));
						Network.getInstance().inviteUserToChan(listUser.get(i).getAddress(), chan,true);
					}
				}
				break;
		}
	}
}

class DataSetObserverPerso extends DataSetObserver{
	int nbLines;
	ListView lv;
	
	public DataSetObserverPerso(int nbLines, ListView lv){
		this.nbLines = nbLines;
		this.lv = lv;		
	}
	
	@Override
    public void onChanged() {
        super.onChanged();
        //lv.setSelection(adapter.getCount() - 1);
        lv.setSelection(nbLines);
	}
	
}